package com.group.transaction.hander;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.group.transaction.domain.Integral;
import com.group.transaction.mapper.IntegralMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * 业务层数据处理
 *
 * @author YunXing Pang
 * @date 2020/4/27
 */
@Component
@Slf4j
public class ServiceDataHandler {

    @Resource
    private IntegralMapper integralMapper;

    /**
     * 异步计算积分
     *
     * @param userId 用户id
     * @param points 积分
     * @return 积分对象
     */
    public Integral calculatePoints(Long userId, Double points) {
        Integral integral = integralMapper.findFirstByUserId(userId);
        if (Objects.isNull(integral)) {
            integral = Integral.builder().userId(userId).integralTotal(points).integralUse(points).integralGive(0.0).integralUnsed(0.0).build();
        } else {
            integral.setIntegralTotal(integral.getIntegralTotal() + points);
            integral.setIntegralUse(integral.getIntegralUse() + points);
        }
        return integral;
    }

    /**
     * 发送短信
     *
     * @param phone   手机号
     * @param content 短信内容
     */
    @Async
    public void sendSms(String phone, String content) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIUQQ7y3Iq3O9n", "cPE5H8F4Ft01klDVc0l0Tm2paMwV29");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "隆林惠民优品");
        request.putQueryParameter("TemplateCode", "SMS_190273322");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+ content +"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

}
